package com.yuncheng.spcyApi.spcyService;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.bo.*;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.busService.InitWjjlService;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.spcyApi.flow.FlowVo;
import com.yuncheng.spcyApi.flow.SpcyFlowConstant;
import com.yuncheng.spcyApi.flow.SpcyFlowService;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.hbjc.HbsxidVo;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Component(value = "spcyService")
public class SpcyService {

    private static final Logger log = LoggerFactory.getLogger(SpcyService.class);

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private SpcyFlowService spcyFlowService;

    @Resource
    @Lazy
    private ISysFlowNodeService sysFlowNodeService;

    @Resource
    @Lazy
    private SqsxQywjclService sqsxQywjclService;

    @Resource
    @Lazy
    private ISpcyQyJbxxService spcyQyJbxxService;

    @Resource
    @Lazy
    private ISpcyRsGcyService spcyRsGcyService;

    @Resource
    @Lazy
    private IYcSysUserService sysUserService;

    @Resource
    @Lazy
    private SpcyVerifyService spcyVerifyService;

    @Resource
    @Lazy
    private SpcyFlfgService spcyFlfgService;

    @Resource
    @Lazy
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    @Lazy
    private InitWjjlService initWjjlService;

    @Resource
    private SpcyHbjcService spcyHbjcService;

    @Resource
    private ISpcyRsWjmbZjmlService spcyRsWjmbZjmlService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    public void syncSqsxFlow(SpcySqsxBasic sqsx){
        String fywflcode = sqsx.getFywflcode();
        if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YLQX)){
            sqsx.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            sqsx.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPZC)){
            sqsx.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            sqsx.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_HZP)){
            sqsx.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            sqsx.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
            sqsx.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            sqsx.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审
        }

        SpcySqsxBasic existsSqsx = spcySqsxBaiscService.selectSqsxById(sqsx.getId());
        if (existsSqsx != null){
            throw new BusinessException("事项已经存在！");
        }
        spcySqsxBaiscService.save(sqsx);

        Result result1 = spcyFlowService.initYwflJob(sqsx.getFywflcode(), sqsx.getId(), GetCurrentUserUtils.getCurrentUser(), false);
        if (!result1.isSuccess()){
            throw new BusinessException(result1.getMessage());
        }
    }

    /** 根据申请事项id-查询申请事项 */
    public SpcySqsxBasic querySqsxById(String sqsxid){
        return spcySqsxBaiscService.getById(sqsxid);
    }

    /** 根据申请事项id-查询申请事项 */
    public SpcySqsxBasic querySqsxInfoById(String sqsxid){
        return spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
    }

    /**
     * 新增申请事项
     * @param fywflcode
     * @param hjmc 指定环节
     * @return
     */
    public Map addSqsxBasic(String fywflcode,String hjmc){
        if (StringUtils.isBlank(fywflcode)){
            throw new BusinessException("操作失败，业务分类编码不能为空！");
        }

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            throw new BusinessException("登录已失效！请重新登录！");
        }

        SpcySqsxBasic basic = new SpcySqsxBasic();
        basic.setId(GetUuIdUtils.ReplaceUuId());
        basic.setFywflcode(fywflcode);
        basic.setFsxsqjbxxid(GetUuIdUtils.ReplaceUuId());
        basic.setFsqsj(new Date());
        basic.setFfssj(new Date());

        if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YLQX)){
            basic.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            basic.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPZC)){
            basic.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            basic.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_HZP)){
            basic.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            basic.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
            basic.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            basic.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }
        basic.setFywflname(SpcyConstant.getYwclNameByCode(fywflcode));
        basic.setFsyts("0");
        basic.setFxzspzt(SpcyConstant.SQSX_BASIC_XZSPZT_RCJG); // 日常监管
        basic.setFfssj(new Date());
        basic.setFclscms(SpcyCommonConstant.SQSX_CLSCMS_YES_XCJC);
        spcySqsxBaiscService.save(basic);
        SpcySqsxJob job = null;

        // 初始化流程
        Result result1 = spcyFlowService.initYwflJob(fywflcode, basic.getId(), currentUser, false);
        if (!result1.isSuccess()){
            throw new BusinessException(result1.getMessage());
        }else {
            job = (SpcySqsxJob) result1.getResult();
        }

        Map map = new HashMap();

        map.put("sqsx", basic);

        map.put("job", job);

        // 获取下环节待办人
        try {
            map.putAll(spcyFlowService.getNextNodeDbr(basic, basic.getId(), null, job));
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return map;
    }

    /**
     * 新增申请事项(日常检查-专项检查)
     * @param fywflcode
     * @param hjmc 指定环节
     * @return
     */
    public HttpResult addZxjcSqsxBasic(String fywflcode, String hjmc){
        if (StringUtils.isBlank(fywflcode)){
            return HttpResult.error("操作失败，业务分类编码不能为空！");
        }

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已失效！请重新登录！");
        }

        SpcySqsxBasic basic = new SpcySqsxBasic();
        basic.setId(GetUuIdUtils.ReplaceUuId());
        basic.setFywflcode(fywflcode);
        basic.setFsxsqjbxxid(GetUuIdUtils.ReplaceUuId());

        if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YLQX)){
            basic.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            basic.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPZC)){
            basic.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            basic.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_HZP)){
            basic.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            basic.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
            basic.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
            basic.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审

        }
        basic.setFywflname(SpcyConstant.getYwclNameByCode(fywflcode));
        basic.setFsyts("0");
        basic.setFxzspzt(SpcyConstant.SQSX_BASIC_XZSPZT_RCJC); // 日常检查
        basic.setFjclx(SpcyConstant.SQSX_BASIC_FJCLX_ZXJC);
        basic.setFfssj(new Date());
        basic.setFclscms(SpcyCommonConstant.SQSX_CLSCMS_YES_XCJC);
        spcySqsxBaiscService.save(basic);
        SpcySqsxJob job = null;

        // 初始化流程
        Result result1 = spcyFlowService.initYwflJob(fywflcode, basic.getId(), currentUser, false);
        if (!result1.isSuccess()){
            throw new BusinessException(result1.getMessage());
        }else {
            job = (SpcySqsxJob) result1.getResult();
        }

        Map map = new HashMap();

        map.put("sqsx", basic);

        map.put("job", job);

        // 获取下环节待办人
        try {
            map.putAll(spcyFlowService.getNextNodeDbr(basic, basic.getId(), null, job));
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return HttpResult.ok(map);
    }

    /**
     * 查询审评查验流程当前环节-上一环节
     * @param jobid 流程任务id
     * @param isZdhj 是否指定环节
     * @return
     */
    public List<Map<String,String>> getCurrentJobPrevious(String jobid,boolean isZdhj){
        if (StringUtils.isBlank(jobid)){
            log.error("流程任务参数为空！{}");

            return new ArrayList<>();
        }
        List<Map<String,String>> ybNodeList = new ArrayList<>();

        SpcySqsxJob nowJob = spcySqsxJobService.getById(jobid);
        if (nowJob == null){
            log.error("当前流程任务不存在！{}", jobid);
            return ybNodeList;
        }

        if (StringUtils.isBlank(nowJob.getFnodeid())){
            throw new BusinessException("当前流程任务结点配置不存在！");
        }

        /** 综合评定-判断是否为免于现场检查 */
        if (StringUtils.isNotBlank(nowJob.getFhjmc())) {

            if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_FAZZ)){

                /** 日常监管验证是否跳转环节 */
                boolean jumpFhjmc = spcySqsxBaiscService.getSqsxRcjgAndZxjcJumpHjmc(nowJob.getFpid());
                if (jumpFhjmc){
                    SpcySqsxJob perNodeJob = spcyFlowService.getCurrentJobNode(nowJob.getFpid(), SpcyFlowConstant.HJMC_RWSL, true);
                    if (perNodeJob != null) {
                        Map<String, String> parMap = new HashMap();
                        parMap.put("id", perNodeJob.getId());
                        parMap.put("fhjmc", perNodeJob.getFhjmc());
                        ybNodeList.add(parMap);
                    }

                    return ybNodeList;
                }
            }
            else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_ZHPD)) {
                /** 合并事项 */
                boolean isHbsqsx = spcyHbjcService.verifyBhbSqsxIsHbsqsx(nowJob.getFpid(), null);
                if (isHbsqsx) {
                    return ybNodeList;
                }

                /** 验证是否存在现场检查 */
                SpcySqsxJob xcjcNodeJob = spcyFlowService.getCurrentJobNode(nowJob.getFpid(), SpcyFlowConstant.HJMC_XCJC, true);
                if (xcjcNodeJob == null) {
                    /** 免于现场检查情况下 */
                    SpcySqsxJob perNodeJob = spcyFlowService.getCurrentJobNode(nowJob.getFpid(), SpcyFlowConstant.HJMC_CLSCFH, true);
                    if (perNodeJob != null) {
                        Map<String, String> parMap = new HashMap();
                        parMap.put("id", perNodeJob.getId());
                        parMap.put("fhjmc", perNodeJob.getFhjmc());
                        ybNodeList.add(parMap);
                    }
                    return ybNodeList;
                }

            }else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_KSFH)
                    || nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_YSQR)){

                SpcySqsxJob perNodeJob = spcyFlowService.getCurrentJobNode(nowJob.getFpid(), SpcyFlowConstant.HJMC_ZHPD, true);
                if (perNodeJob != null) {
                    Map<String, String> parMap = new HashMap();
                    parMap.put("id", perNodeJob.getId());
                    parMap.put("fhjmc", perNodeJob.getFhjmc());
                    ybNodeList.add(parMap);
                }

                return ybNodeList;

            }else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_FASH)
                    || nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_FASP)){

                SpcySqsxJob perNodeJob = spcyFlowService.getCurrentJobNode(nowJob.getFpid(), SpcyFlowConstant.HJMC_FAZZ, true);
                if (perNodeJob != null) {
                    Map<String, String> parMap = new HashMap();
                    parMap.put("id", perNodeJob.getId());
                    parMap.put("fhjmc", perNodeJob.getFhjmc());
                    ybNodeList.add(parMap);
                }

                return ybNodeList;
            }
        }

        /** 根据不同流程名称返回对应的流程 */
        if (StringUtils.isNotBlank(nowJob.getFlcmc())){
            /** 退回政务流程 */
            if (nowJob.getFlcmc().contains(SpcyFlowConstant.THZWFW_LCMC)){
                SpcySqsxJob perNodeJob = spcyFlowService.getNowNodeSpcyJob(nowJob.getFpid(), false, SpcyFlowConstant.HJMC_CLSC, false);
                if (perNodeJob != null) {
                    Map<String, String> parMap = new HashMap();
                    parMap.put("id", perNodeJob.getId());
                    parMap.put("fhjmc", perNodeJob.getFhjmc());
                    ybNodeList.add(parMap);
                }
                return ybNodeList;

            }else if (nowJob.getFlcmc().contains(SpcyFlowConstant.BQBZ_LCMC)){
                /** 补齐补正流程 */
                SpcySqsxJob perNodeJob = spcyFlowService.getNowNodeSpcyJob(nowJob.getFpid(), false, SpcyFlowConstant.HJMC_CLSC, false);
                if (perNodeJob != null) {
                    Map<String, String> parMap = new HashMap();
                    parMap.put("id", perNodeJob.getId());
                    parMap.put("fhjmc", perNodeJob.getFhjmc());
                    ybNodeList.add(parMap);
                }
                return ybNodeList;
            }

        }

        /** 流程配置当前结点的上一个结点 */
        List<SysFlowNode> previousNodeList = sysFlowNodeService.getPreviousNode(nowJob.getFnodeid());
        if (CollectionUtil.isEmpty(previousNodeList)){
            return ybNodeList;
        }

        LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxJob::getFpid, nowJob.getFpid());
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);

        if (previousNodeList.size() == 1) {
            queryWrapper.eq(SpcySqsxJob::getFnodeid, previousNodeList.get(0).getId());
        }else {
            List<String> preIdsList = previousNodeList.stream().map(SysFlowNode::getId).collect(Collectors.toList());
            queryWrapper.in(SpcySqsxJob::getFnodeid, preIdsList);
        }

        // 上环节结点id-办理过的流程任务
        List<SpcySqsxJob> previousJobList = spcySqsxJobService.list(queryWrapper);

        if (CollectionUtil.isNotEmpty(previousJobList)){
            Map<String,String> parMap = new HashMap();
            parMap.put("id", previousJobList.get(0).getId());
            parMap.put("fhjmc", previousJobList.get(0).getFhjmc());
            ybNodeList.add(parMap);
        }

        /*for (int i=0; i<previousJobList.size(); i++){
            Map<String,String> parMap = new HashMap();
            parMap.put("id", previousJobList.get(i).getId());
            parMap.put("fhjmc", previousJobList.get(i).getFhjmc());
            ybNodeList.add(parMap);
        }*/

        // map: {id,fhjmc}
        return ybNodeList;
    }

    /**
     * 删除任务登记事项-通过流程任务ids
     */
    public void delRwdjJob(String jobids){
        List<String> jobidList = StringPatternUtils.getListByIds(jobids);
        List<SpcySqsxJob> jobList = spcySqsxJobService.listByIds(jobidList);

        String log = "";
        for (SpcySqsxJob job : jobList) {
            // 当前流程对应的申请事项
            SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxById(job.getFpid());

            // 不属于的政务数据，允许删除
            if (sqsx != null && !sqsx.getFxzspzt().equals(SpcyConstant.SQSX_BASIC_XZSPZT_YES)) {

                boolean flag = spcySqsxBaiscService.removeById(job.getFpid());// 删除申请事项
                if (flag) {

                    // 删除流转记录
                    spcySqsxJobService.remove(new LambdaQueryWrapper<SpcySqsxJob>()
                            .eq(SpcySqsxJob::getFpid, job.getFpid()));

                    // 删除材料
                    sqsxQywjclService.batchDeleteRwdjQywjcl(job.getFpid());

                    // 事项文件
                    initWjjlService.batchDeleteRwdjSqsxWj(job.getFpid());

                    log = "";
                    log = "删除事项基本信息["+job.getFhjmc()+"]: ";
                    log += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(sqsx));
                    spcyLogService.addLogs(LogConstant.LOGS_SQSX_BASIC, log, job.getFpid(), "删除任务登记事项", SpcyConstant.LOGS_SYS_TYPE_SC);
                }
            }

            log = "";
            log = "删除申请事项流程["+job.getFhjmc()+"]: ";
            log += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(job));
            spcyLogService.addLogs(LogConstant.LOGS_SQSX_BASIC,log,job.getFpid(), "删除任务登记事项", SpcyConstant.LOGS_SYS_TYPE_SC);
        }
    }

    /**
     * 批量提交
     * */
    public void batchSubmitJob(BatchSubmitJobParamBo paramVo){
        if (StringUtils.isBlank(paramVo.getJobids())){
            throw new BusinessException("请选择待办数据！");
        }

        spcyVerifyService.verifySfpltj(paramVo.getJobids());

        if (StringUtils.isBlank(paramVo.getOpinion())){
            throw new BusinessException("办理意见不能为空！");
        }
        if (StringUtils.isBlank(paramVo.getDbrid())){
            throw new BusinessException("待办人不能为空！");
        }
        List<String> jobIdList = StringPatternUtils.getListByIds(paramVo.getJobids());
        for (String jobid : jobIdList) {
            FlowVo flowVo = new FlowVo();
            flowVo.setJobid(jobid);
            flowVo.setOpinion(paramVo.getOpinion());
            flowVo.setDbrid(paramVo.getDbrid());
            Result httpResult1 = spcyFlowService.handleFlow(flowVo, flowVo.getJobid(), SpcyFlowConstant.SUBMIT_TYPE_SUBMIT, flowVo.getOpinion());
            if (!httpResult1.isSuccess()) {
                throw new BusinessException(httpResult1.getMessage());
            }
        }
    }

    /**
     * 将（不可办）流程任务转为（可办）办理
     */
    public void updateKbJobInBkb(JobAdvanceParamsBo paramsBo){
        if (StringUtils.isBlank(paramsBo.getJobid())){
            throw new BusinessException("请选择数据！");
        }

        List<String> jobIdList = StringPatternUtils.getListByIds(paramsBo.getJobid());

        for (String id : jobIdList) {
            LambdaUpdateWrapper<SpcySqsxJob> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SpcySqsxJob::getId, id);

            SpcySqsxJob updateJob = new SpcySqsxJob();
            updateJob.setFlcsfkb(SpcyFlowConstant.JOB_LCSFKB_TJB);
            updateJob.setFbz(paramsBo.getFbz());
            spcySqsxJobService.update(updateJob, updateWrapper);
        }
    }

    /**
     * 获取汇总材料目录-审查意见
     */
    public String getSummaryOpinionInScyj(String sqsxid){
        String opinion = sqsxQywjclService.summaryOpinionInScyj(sqsxid);

        return opinion;
    }

    /**
     * 验证是否存在审查意见
     */
    public boolean verifyQywjSfczScyj(String sqsxid){

        return sqsxQywjclService.verifyWjmlSfczScyj(sqsxid);
    }

    /**
     * 生成申请事项-检查通讯录功能
     */
    public List<List<String>> generateSqsxInspectAddressBook(String sqsxid){
        List<List<String>> resultList = new ArrayList<>();

        List<String> titleList = CollectionUtil.newArrayList("序号","通讯录","联系人","电话","邮箱");
        resultList.add(titleList);

        List<String> dataList = null;

        int count = 1;
        /** 审评中心联系人 */
        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx != null){
            if (StringUtils.isNotBlank(sqsx.getFzbr())){
                List<String> userIdList = StringPatternUtils.getListByIds(sqsx.getFzbr());
                List<YcSysUser> userList = sysUserService.listByIds(userIdList);
                for (int u=0; u<userList.size(); u++){
                    dataList = new ArrayList<>();

                    dataList.add(String.valueOf(count));
                    count++;

                    dataList.add("审评中心");
                    dataList.add(Optional.ofNullable(userList.get(u).getRealname()).orElseGet(()->""));
                    dataList.add(Optional.ofNullable(userList.get(u).getPhone()).orElseGet(()->""));
                    dataList.add(Optional.ofNullable(userList.get(u).getEmail()).orElseGet(()->""));
                    resultList.add(dataList);
                }
            }

            if (StringUtils.isNotBlank(sqsx.getFqyid())){
                SpcyQyJbxx qy = spcyQyJbxxService.getById(sqsx.getFqyid());
                if (qy != null){
                    dataList = new ArrayList<>();

                    dataList.add(String.valueOf(count));
                    count++;

                    if (StringUtils.isNotBlank(qy.getFqymc())) {
                        dataList.add("企业名称(" + qy.getFqymc() + ")");
                    }else {
                        dataList.add("企业名称");
                    }
                    dataList.add(Optional.ofNullable(qy.getFqylxr()).orElseGet(()->""));
                    dataList.add(Optional.ofNullable(qy.getFqylxrdh()).orElseGet(()->""));
                    dataList.add(Optional.ofNullable(qy.getFqylxryx()).orElseGet(()->""));
                    resultList.add(dataList);
                }
            }

            /** 观察员联系人 */
            if (StringUtils.isNotBlank(sqsx.getFcygcyid())){
                SpcyRsGcy gcy = spcyRsGcyService.getById(sqsx.getFcygcyid());
                if (gcy != null){
                    dataList = new ArrayList<>();

                    dataList.add(String.valueOf(count));
                    count++;

                    if (StringUtils.isNotBlank(gcy.getFdwmc())) {
                        dataList.add("监管部门(" + gcy.getFdwmc() + ")");
                    }else {
                        dataList.add("监管部门");
                    }
                    dataList.add(Optional.ofNullable(gcy.getFgcyxm()).orElseGet(()->""));
                    dataList.add(Optional.ofNullable(gcy.getFphone()).orElseGet(()->""));
                    dataList.add(Optional.ofNullable(gcy.getFemail()).orElseGet(()->""));
                    resultList.add(dataList);
                }
            }

        }

        /** 检查员 联系人 */
        List<SpcySqsxXpjl> cyXpList = busService.getTyXpXpjlList(sqsxid, SpcyConstant.FLOW_TYPE_CY);
        for (int j=0; j<cyXpList.size(); j++){
                dataList = new ArrayList<>();

                dataList.add(String.valueOf(count));
                count++;

                if (StringUtils.isBlank(cyXpList.get(j).getFssk())){
                    dataList.add("检查员");
                }else {
                    if (cyXpList.get(j).getFssk().contains(SpcyConstant.HCY_SSK_ZZ)) {
                        dataList.add("检查员（" + SpcyConstant.HCY_SSK_ZZ + ")");
                    } else if (cyXpList.get(j).getFssk().contains(SpcyConstant.HCY_SSK_ZY)) {
                        dataList.add("检查员（" + SpcyConstant.HCY_SSK_ZY + ")");
                    } else if (StringUtils.isNotBlank(cyXpList.get(j).getFssk())) {
                        dataList.add("检查员（" + cyXpList.get(j).getFssk() + ")");
                    }
                }
                YcSysUser user = sysUserService.getById(cyXpList.get(j).getFuserid());
                if (user == null) {
                    dataList.add("");
                    dataList.add("");
                    dataList.add("");
                }else {
                    dataList.add(Optional.ofNullable(user.getRealname()).orElseGet(()->""));
                    dataList.add(Optional.ofNullable(user.getPhone()).orElseGet(()->""));
                    dataList.add(Optional.ofNullable(user.getEmail()).orElseGet(()->""));
                }
                resultList.add(dataList);
        }

        return resultList;
    }

    /**
     * 获取现场检查发现人员列表
     * @return
     * [{userid: 用户id, name: 姓名}]
     */
    public Map getXcjcFxryList(String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return null;
        }

        Map resultMap = new HashMap();
        List<Map> dataListMap = new ArrayList<>();
        List<SpcySqsxXpjl> list = spcyFlowService.getTyXpryList(sqsxid, SpcyConstant.FLOW_TYPE_CY);

        Map jczMap = new HashMap();
        jczMap.put("userid", SpcyCommonConstant.FLFG_XCJCWT_FXRYID_JCZID);
        jczMap.put("name", SpcyCommonConstant.FLFG_XCJCWT_FXRYID_JCZXM);
        dataListMap.add(jczMap);

        for (int i=0; i<list.size(); i++){
            Map par = new HashMap();

            par.put("userid", list.get(i).getFuserid());
            par.put("name", list.get(i).getFjcyxm()+"/"+list.get(i).getFssk());

            dataListMap.add(par);
        }

        resultMap.put("list", dataListMap);
        resultMap.put("nowUserId", GetCurrentUserUtils.getCurrentUserId());
        return resultMap;
    }

    /**
     * 获取现场检查章节任务分配人员列表
     * @return
     * [{userid: 用户id, name: 姓名}]
     */
    public List<Map> getXcjcRwfpPersonListNew(String sqsxid){
        List<Map> resultMap = new ArrayList<>();

        List<SpcySqsxXpjl> list = new ArrayList<>();
        boolean isHbsx = false;
        String hbsxid = spcySqsxBaiscService.selectFhbsxidsById(sqsxid);
        if (StringUtils.isNotBlank(hbsxid)) {
            isHbsx = true;
            list = spcyFlowService.getTyXpryList(hbsxid, SpcyConstant.FLOW_TYPE_CY);
        }else {
            list = spcyFlowService.getTyXpryList(sqsxid, SpcyConstant.FLOW_TYPE_CY);
        }

        Map par = null;

        List<SpcyFgXcjczj> jczjList = spcyFlfgService.queryXcjcZjBySqsxId(sqsxid);

        for (int i=0; i < list.size(); i++){
            par = new HashMap();

            boolean isZz = false;
            if (StringUtils.isNotBlank(list.get(i).getFssk())){
                if (list.get(i).getFssk().equals(SpcyConstant.HCY_SSK_ZZ)){
                    isZz = true;
                }
            }

            par.put("userid", list.get(i).getFuserid());
            par.put("name", list.get(i).getFjcyxm());
            par.put("jcsf", list.get(i).getFssk());

            /*List<SpcyFgXcjczj> zjContentList = new ArrayList<>();
            if (isZz){
                zjContentList = spcyFlfgService.queryXcjcZjBySqsxId(sqsxid);
            }else {
                zjContentList = spcyFlfgService.queryXcjcZjBySqsxId(sqsxid, list.get(i).getFuserid());
            }

            String zjContent = "";
            if (CollectionUtil.isNotEmpty(zjContentList)) {
                for (SpcyFgXcjczj zj : zjContentList) {
                    if (StringUtils.isNotBlank(zjContent)) {
                        zjContent += "\n" + zj.getFzjmc();
                    } else {
                        zjContent += zj.getFzjmc();
                    }
                    zjContent += " ";
                }
            }*/
            par.put("zjContent", this.getJcZjContent(sqsxid, jczjList, isZz, list.get(i).getFuserid(), isHbsx, hbsxid));

            resultMap.add(par);
        }

        return resultMap;
    }

    /**
     * 现场检查章节-拼接获取章节内容
     */
    private String getJcZjContent(String sqsxid, List<SpcyFgXcjczj> jczjList, boolean isZz, String userid, boolean isHbsx, String hbsxid){


        if (CollectionUtil.isNotEmpty(jczjList)){
            List<SpcyFgXcjczj> zjContentList = new ArrayList<>();
            if (isZz){
//                zjContentList = jczjList;
                zjContentList = jczjList.stream()
                        .filter(f -> StringUtils.isBlank(f.getFtxfzrid()))
                        .collect(Collectors.toList());
            }else {
                zjContentList = jczjList.stream()
                        .filter(f->StringUtils.isNotBlank(f.getFtxfzrid())
                                && f.getFtxfzrid().equals(userid)
                        )
                        .collect(Collectors.toList());
            }

            String zjContent = "";

            if (CollectionUtil.isNotEmpty(zjContentList)) {
                for (SpcyFgXcjczj zj : zjContentList) {
                    zjContent += StringUtils.isNotBlank(zjContent) ? "\n" : "";
                    zjContent += zj.getFzjmc();
                    zjContent += " ";
                }
            }

            return zjContent;
        }
        else {
            return this.getWjmbZjContent(sqsxid, isZz, userid, isHbsx, hbsxid);
        }
    }

    /**
     * 检查报告-模板章节-拼接获取章节内容
     * @param isZz true: 组长
     */
    private String getWjmbZjContent(String sqsxid, boolean isZz, String userid, boolean isHbsx, String hbsxid){

        List<SpcyRsWjmbZjml> mbZjList = new ArrayList<>();
        if (isHbsx){
            mbZjList = spcyRsWjmbZjmlService.selectZjByHbsxId(hbsxid, sqsxid);
        }else {
            mbZjList = spcyRsWjmbZjmlService.selectWjmbZjmlList(sqsxid);
        }

        if (isZz){
            mbZjList = mbZjList.stream()
                    .filter(f->StringUtils.isBlank(f.getFtxfzrid()))
                    .collect(Collectors.toList());
        }else {
            mbZjList = mbZjList.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFtxfzrid()) && f.getFtxfzrid().equals(userid))
                    .collect(Collectors.toList());
        }

        String zjContent = "";
        if (CollectionUtil.isNotEmpty(mbZjList)) {
            for (SpcyRsWjmbZjml zj : mbZjList) {
                zjContent += StringUtils.isNotBlank(zjContent) ? "\n" : "";
                zjContent += "（" + ChineseNumberConverterUtils.convertToChinese(zj.getForder()) + "）" + zj.getFzjmc();
                zjContent += " ";
            }
        }

        return zjContent;
    }

    /**
     * 获取任务分配人员-对应的分配章节列表
     */
    public List<Map> getRwfpRyZjList(String sqsxid, String userid){
        List<SpcyFgXcjczj> fpList = spcyFlfgService.queryXcjcZjBySqsxId(sqsxid);


        List<Map> fpZjList = new ArrayList<>();
        Map dataMap = null;
        int order = 1;

        if (CollectionUtil.isNotEmpty(fpList)) {
            for (SpcyFgXcjczj fp : fpList) {
                dataMap = new HashMap();
                dataMap.put("order", order);
                dataMap.put("id", fp.getId());
                dataMap.put("zjmc", fp.getFzjmc());

                if (StringUtils.isBlank(fp.getFtxfzrid())) {
                    dataMap.put("bz", "添加");
                } else if (fp.getFtxfzrid().equals(userid)) {
                    dataMap.put("bz", "移除");
                } else {
                    continue;
                }

                order++;
                fpZjList.add(dataMap);
            }

        }
        else {
            /** 区分合并事项 */
            boolean isHbsx = false;
            String hbsxid = spcySqsxBaiscService.selectFhbsxidsById(sqsxid);
            if (StringUtils.isNotBlank(hbsxid)){
                isHbsx = true;
            }

            /** 模板章节 */
            List<SpcyRsWjmbZjml> mbZjList = new ArrayList<>();
            if (isHbsx){
                mbZjList = spcyRsWjmbZjmlService.selectZjByHbsxId(hbsxid, sqsxid);
            }else {
                mbZjList = spcyRsWjmbZjmlService.selectWjmbZjmlList(sqsxid);
            }

            for (SpcyRsWjmbZjml mbzj : mbZjList){
                dataMap = new HashMap();

                dataMap.put("order", order);
                dataMap.put("id", "mbzj@"+mbzj.getId());
                dataMap.put("zjmc", "（" + ChineseNumberConverterUtils.convertToChinese(mbzj.getForder()) + "）" + mbzj.getFzjmc());

                if (StringUtils.isBlank(mbzj.getFtxfzrid())) {
                    dataMap.put("bz", "添加");
                } else if (mbzj.getFtxfzrid().equals(userid)) {
                    dataMap.put("bz", "移除");
                } else {
                    continue;
                }

                order++;
                fpZjList.add(dataMap);
            }
        }

        return fpZjList;
    }

    /**
     * 验证当前用户-是否为选派人员-是否为组长
     * @param sqsxid 申请事项id
     * @return true: 为组长
     */
    public boolean verifyNowUserIsXpryZz(String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return true;
        }

        return spcyVerifyService.verifyNowUserIsXpryZz(sqsxid, GetCurrentUserUtils.getCurrentUserId());
    }

    /**
     * 验证企业申请材料文件目录可读权限
     * @return true: 可读
     */
    public boolean verifyQywjclAndMlReadableState(String sqsxid){
        return spcyVerifyService.verifyNowJobInXcjcNode(sqsxid);
    }

    /**
     * 查询方案制作-检查方案文件记录
     * @param sqsxid 申请事项id
     */
    public List<SpcySqsxWjjl> queryJcfaFile(String sqsxid){
        return spcySqsxWjjlService.getWjjlListByPidAndType(sqsxid, WjmlConstant.jcfa, true);
    }

    /**
     * 验证是否已经存在检查方案 (0: 不存在，1：存在)
     */
    public HttpResult verifyExistsJcfaFile(String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("操作失败，缺少事项参数！");
        }

        if (CollectionUtil.isNotEmpty(spcySqsxWjjlService.verifyExistsWjjl(sqsxid, WjmlConstant.jcfa))){
            return HttpResultVo.HttpResultSave(1, "操作成功");
        }

        return HttpResultVo.HttpResultSave(0, "操作成功");
    }

    /**
     * 查询文件记录
     * @param sqsxid 申请事项id
     */
    public List<SpcySqsxWjjl> queryWjjlByType(String sqsxid, String type){
        return spcySqsxWjjlService.getWjjlListByPidAndType(sqsxid, type, true);
    }

    /**
     * 获取现场检查报告文件
     * @param sqsxid 申请事项id
     */
    public List<SpcySqsxWjjl> getXcjcbgFile(String sqsxid){
        return spcySqsxWjjlService.getWjjlListByPidAndType(sqsxid, WjmlConstant.xcjcbg, true);
    }

    /**
     * 获取现场检查缺陷报告文件
     * @param sqsxid 申请事项id
     */
    public List<SpcySqsxWjjl> getXcjcqxbgFile(String sqsxid){

        /** 合并事项兼容 */
        HbsxidVo hbsxidVo = spcySqsxBaiscService.selectHbsxidAndCodeById(sqsxid);
        if (hbsxidVo == null){
            return null;
        }

        if (hbsxidVo.getFhbsxzt() != null && hbsxidVo.getFhbsxzt() == 1) {
            return spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                    .in(SpcySqsxWjjl::getFpid, StringPatternUtils.getListByIds(hbsxidVo.getFhbsxids()))
                    .eq(SpcySqsxWjjl::getFwjlx1, WjmlConstant.xcjcqxjlb));
        }

        return spcySqsxWjjlService.getWjjlListByPidAndType(sqsxid, WjmlConstant.xcjcqxjlb, true);
    }

    /**
     * 获取综合评定报告书文件
     * @param sqsxid 申请事项id
     */
    public List<SpcySqsxWjjl> getZhpdbgFile(String sqsxid){
        return spcySqsxWjjlService.getWjjlListByPidAndType(sqsxid, WjmlConstant.zhpdbgs, true);
    }

    /**
     * 获取移送函文件
     * @param sqsxid 申请事项id
     */
    public List<SpcySqsxWjjl> getZhpdYshFile(String sqsxid){
        return spcySqsxWjjlService.getWjjlListByPidAndType(sqsxid, WjmlConstant.yshmb, true);
    }

    /**
     * 更新现场检查任务分配状态
     */
    public void updateXcjcRwfpState(String sqsxid){
        spcySqsxBaiscService.updateSqsxRwfpState(sqsxid);
    }

    /**
     * 更新申请事项-缺陷信息
     * @param sqsxid
     */
    public void updateSqsxXcjcQxxx(String sqsxid,SqsxXcjcQxParamBo qxParamBo){
        LambdaUpdateWrapper<SpcySqsxBasic> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcySqsxBasic::getId, sqsxid);

        SpcySqsxBasic updateSqsx = new SpcySqsxBasic();
        updateSqsx.setFcyybqx(qxParamBo.getYbqx());
        updateSqsx.setFcyzyqx(qxParamBo.getZyqx());
        updateSqsx.setFcyyzqx(qxParamBo.getYzqx());
        updateSqsx.setFcyjg(qxParamBo.getFcyjg());
        if (StringUtils.isNotBlank(qxParamBo.getFcyjcyj())) {
            updateSqsx.setFcyjcyj(qxParamBo.getFcyjcyj());
        }
        updateSqsx.setFjcqxxm(qxParamBo.getFjcqxxm());
//        updateSqsx.setFcyjl(qxParamBo.getJl());
        spcySqsxBaiscService.update(updateSqsx, updateWrapper);

    }

    /**
     * 保存检查情况转述
     */
    public Result updateSqsxBasic(HashMap<String,Object> updaeMap, String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return Result.error("事项参数为空！");
        }

        SpcySqsxBasic oldBasic = spcySqsxBaiscService.getById(sqsxid);
        if (oldBasic == null){
            return Result.error("当前申请事项【"+sqsxid+"】不存在，请重试");
        }

        SpcySqsxBasic basicUpdate = oldBasic;
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        try {
            BeanUtils.populate(basicUpdate, updaeMap);
        }catch (IllegalAccessException e) {
            log.error("出错-保存申请事项【非法访问异常】,{}",e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("出错-保存申请事项【调用TargetException】,{}",e.getMessage());
        }
        basicUpdate.setId(sqsxid);
        spcySqsxBaiscService.updateById(basicUpdate);

        String logContent = "申请事项基本信息修改: ";
        logContent += LogUtils.BeanModifyMsg(basicUpdate, ObjectToMapUtils.objectToMap(oldBasic));

        spcyLogService.addLogs(LogConstant.LOGS_SQSX_BASIC, logContent, sqsxid, "修改申请事项信息", SpcyConstant.LOGS_SYS_TYPE_XG);

        return Result.ok();
    }

    /** 生成整改通知内容 */
    public String getZgtznr(String sqsxid){

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxSxxxById(sqsxid);
        if (sqsx == null){
            return "";
        }

        if (sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPSC)){
            return getZgtznr001002(sqsx);
        }
        else if (sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPZC)){

        }
        else if (sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPJY)){

        }
        else if (sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YLQX)){

        }else if (sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_HZP)){

        }

        return "";
    }

    /** 生成整改通知内容-药品生产 */
    private String getZgtznr001002(SpcySqsxBasic sqsx){
        StringBuilder content = new StringBuilder();

        content.append(Optional.ofNullable(sqsx.getFqymc()).orElse(""));
        content.append(": \n").append("    ");
        content.append("根据《药品管理法》、《药品生产监督管理办法》、药品 GMP（2010 年修订）" +
                "和《药品检查管理办法》（试行）规定，为规范药品生产企业和医疗机构提交药品检查整改材料，特制订本要求。");

        content.append("\n").append("    ");
        content.append("一、现场检查结束后，被检查单位应当在 20 个工作日内针对缺陷项目进行整改；无法按期完成整改的，" +
                "应当制定切实可行的整改计划，并作为对应缺陷的整改完成情况列入整改报告，整改报告提交给自治区食品药品审评查验中心。");

        content.append("\n").append("    ");
        content.append("二、整改报告应当至少包含缺陷描述、缺陷调查分析、风险评估、风险控制、整改审核、整改效果评价等内容，" +
                "针对缺陷成因及风险评估情况，逐项描述风险控制措施及实施结果。");

        content.append("\n").append("    ");
        content.append("三、被检查单位按照整改计划完成整改后，及时将整改情况形成补充整改报告报送自治区食品药品审评查验中心综合" +
                "业务科，收件地址：南宁市云景路 32 号广西食品药品审评查验中心综合业务科(转药品生产查验科)，电话：0771-5886193。" +
                "必要时，中心可以对被检查单位整改落实情况进行现场检查。");

        content.append("\n\n");
        content.append("                    ").append(DateConversionUtils.DateToStringNew(new Date()));

        return content.toString();
    }

}
